package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Orders;
import com.itheima.common.R;
import com.itheima.service.OrderService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RequestMapping("/order")
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders order){
        //1.调用service完成业务处理
        orderService.submit(order);

        //2.返回下单成功
        return R.success("下单成功！");
    }

    //订单分页查询
    @GetMapping("/page")
    public R< Page<Orders>> aaa(@RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "10") Integer pageSize,
                                String number,
                                @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime beginTime,
                                @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime){


        //1.创建Page对象，设置分页参数【当前页码、每页显示条数】
        Page<Orders> ordersPage = new Page<>(page, pageSize);

        //2.1.创建wrapper对象 设置查询条件【订单号 number】
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.like(number!=null&&number.length()>0,Orders::getNumber,number);

        //2.2.创建wrapper对象 设置查询条件【时间 beingTime  endTime】
        ordersLambdaQueryWrapper.between(beginTime!=null&&endTime!=null,Orders::getCheckoutTime,beginTime,endTime);

        //3.调用Service方法完成分页查询
        orderService.page(ordersPage,ordersLambdaQueryWrapper);

        return R.success(ordersPage);
    }

    @GetMapping("/userPage")
    public R<Page<Orders>> findPage(Integer page,Integer pageSize){


        Page<Orders> ordersPage = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();

        wrapper.orderByDesc(pageSize==1,Orders::getOrderTime);

        orderService.page(ordersPage,wrapper);

        return R.success(ordersPage);
    }

    @PutMapping
    public R<String> putStatus(@RequestBody Orders orders){

        Orders orders1 = orderService.getById(orders);
        orders1.setStatus(orders1.getStatus()+1);

        orderService.updateById(orders1);

        return R.success("更改成功");

    }

}